package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.emp02list.impl.ResultListGcsImpl;
import cc.eddic.pratice.programmingparadigms.nginxlog.LogItem;
import cc.eddic.pratice.programmingparadigms.nginxlog.LogItemParser;
import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Optional;

public class LogItemParserLxImpl implements LogItemParser {
    private static final Logger log = LoggerFactory.getLogger(ResultListGcsImpl.class);

    @Override
    public Optional<LogItem> parse(NginxLogItem nginxLogItem) {
        LocalDateTime localDateTime = LocalDateTime.now();
        String[] request=nginxLogItem.getRequest().split(" ");
        if(request.length==3){
            String method=request[0];
            String protocol=request[2];
            String url=request[1];
            String path;
            if(url.contains("?")){
                int index=url.indexOf('?');
                path=url.substring(0,index);
                if (log.isDebugEnabled()) log.debug("path: {}", path);
            }else{
                path=url;
            }
            return Optional.of(new LogItem(nginxLogItem.getIp(),localDateTime,method,path,new HashMap<>(),
                    protocol,Integer.parseInt(nginxLogItem.getStatus()),Long.parseLong(nginxLogItem.getBytes()),
                    nginxLogItem.getReferer(),nginxLogItem.getUserAgent()));
        }else{
            return Optional.empty();
        }
    }


}
